package com.jzy.service.impl;

import com.jzy.entity.Vo.UserVo;
import com.jzy.exception.TipException;
import com.jzy.repository.UserRepository;
import com.jzy.service.IUserService;
import com.jzy.util.TaleUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserServiceImpl implements IUserService {
    @Resource
    private UserRepository userRepository;
    //登录
    @Override
    public UserVo login(String username, String password) {
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            throw new TipException("用户名和密码不能为空");
        }
        UserVo byUsername = userRepository.getByUsername(username);
        if (byUsername == null) {
            throw new TipException("不存在该用户");
        }
        String pwd = TaleUtils.MD5encode(username+password);
        UserVo byUsernameAndPassword = userRepository.getByUsernameAndPassword(username, pwd);
        if (byUsernameAndPassword == null) {
            throw new TipException("用户名或密码错误");
        }
        return byUsernameAndPassword;
    }

    @Override
    public UserVo insertUser(UserVo userVo) {
        if (StringUtils.isNotBlank(userVo.getUsername()) && StringUtils.isNotBlank(userVo.getEmail())) {
            // 用户密码加密
            String encodePwd = TaleUtils.MD5encode(userVo.getUsername() + userVo.getPassword());
            userVo.setPassword(encodePwd);
            return userRepository.saveAndFlush(userVo);
        }
        return null;
    }

    @Override
    public UserVo queryUserById(Integer uid) {
        return userRepository.findById(uid).orElse(null);
    }

    @Override
    public void updateByUid(UserVo userVo) {
        if (null == userVo || null == userVo.getUid()) {
            throw new TipException("userVo is null");
        }
        userRepository.saveNotNull(userVo);
    }
}
